import Toast from 'tdesign-miniprogram/toast/index';
// 接口
import { fetchShopSptype, fetchShopIndex, fetchShopAddcart } from '~/request/api';
// 登录
import login from '~/common/login';

Page({
  data: {
    imgSrcs: [],
    tabList: [],
    pageLoading: false,
    current: 1,
    autoplay: true,
    duration: '500',
    interval: 5000,
    navigation: { type: 'dots' },
    swiperImageProps: { mode: 'scaleToFill' },
    indexInfo: {
      recommend_list: [], // 推荐
      new_list: [], // 新品
      hot_list: [], // 热门
    },
  },

  onShow() {
    this.getTabBar().init();
  },

  onLoad() {
    this.init();
  },

  onReachBottom() { },

  onPullDownRefresh() {
    this.init();
  },

  async init() {
    const token = wx.getStorageSync('token') || '';
    if (!token) {
      // 获取登录token
      const token = await login();
      wx.setStorageSync('token', token);
      this.loadHomePage();
      this.shopSptype();
    } else {
      this.loadHomePage();
      this.shopSptype();
    }
  },

  // 获取类目
  async shopSptype() {
    try {
      const res = await fetchShopSptype();
      this.setData({ tabList: res?.children?.splice(0, 5) });
    } catch (error) {
      console.log(error);
    }
  },

  // 获取商城首页
  async shopIndex() {
    try {
      const res = await fetchShopIndex();
      const imgSrcs = res.nav_list.map((item) => item.logo);
      this.setData({ indexInfo: res, imgSrcs, pageLoading: false });
    } catch (error) {
      console.log(error);
    }
  },

  loadHomePage() {
    wx.stopPullDownRefresh();

    this.setData({
      pageLoading: true,
    });
    this.shopIndex();
  },

  // 点击类目回调
  handleTab(e) {
    const { id } = e.currentTarget;
    wx.navigateTo({
      url: `/pages/home/category/index?tab=${id}`,
    });
    // wx.navigateTo({
    //   url: `/pages/goods/category/index?tab=${id}`,
    // });
  },

  handleCart() {
    wx.navigateTo({
      url: '/pages/cart/index',
    });
  },

  // 跳转商品详情
  goodListClickHandle(e) {
    const { goods } = e.detail;
    wx.navigateTo({
      url: `/pages/goods/details/index?goods_id=${goods.id}`,
    });
  },

  // 添加购物车
  async shopAddcart(params) {
    try {
      const res = await fetchShopAddcart(params);
      Toast({
        context: this,
        selector: '#t-toast',
        message: res.msg,
        icon: '',
        duration: 1000,
      });
    } catch (error) {
      console.log(error);
    }
  },

  // 点击加入购物车
  goodListAddCartHandle(e) {
    const { goods } = e.detail;
    this.shopAddcart({ goods_id: goods.id, num: 1 });
  },

  navToSearchPage() {
    wx.navigateTo({ url: '/pages/goods/search/index' });
  },

  navToActivityDetail({ detail }) {
    const list = this.data.indexInfo?.nav_list || [];
    const id = list[detail.index].id;
    wx.navigateTo({
      url: `/pages/goods/details/index?goods_id=${id}`,
    });
  },
});
